package gspringboot

import (
	"errors"
	"strings"
)

// commandLineArgsParse 解析命令行参数
// for example: --gspring.profiles.active=dev
func commandLineArgsParse(args ...string) *CommandLineArgs {
	commandLineArgs := newCommandLineArgs()
	for _, arg := range args {
		var optText string
		if strings.HasPrefix(arg, "--") {
			optText = arg[2:]
		} else if strings.HasPrefix(arg, "-") {
			optText = arg[1:]
		} else {
			panic(errors.New("invalid command line arg: " + arg))
		}

		var optName string
		var optVal string
		eqIndex := strings.IndexByte(optText, '=')
		if eqIndex == -1 {
			optName = arg
		} else {
			optName = optText[:eqIndex]
			optVal = optText[eqIndex+1:]
		}
		if optName == "" {
			panic(errors.New("invalid command line arg: " + arg))
		}
		commandLineArgs.AddOptArg(optName, optVal)
	}
	return commandLineArgs
}

func newCommandLineArgs() *CommandLineArgs {
	return &CommandLineArgs{
		args: make(map[string][]string),
	}
}

// CommandLineArgs 命令行参数对象
type CommandLineArgs struct {
	args map[string][]string
}

func (my *CommandLineArgs) AddOptArg(optName, optVal string) {
	optVals, ok := my.args[optName]
	if ok {
		my.args[optName] = append(optVals, optVal)
	} else {
		my.args[optName] = []string{optVal}
	}
}

func (my *CommandLineArgs) GetVal(optName string) []string {
	return my.args[optName]
}

func (my *CommandLineArgs) ContainsKey(optName string) bool {
	_, ok := my.args[optName]
	return ok
}
